package com.test.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csvreader.CsvReader;
import com.test.dao.MyTestRepository;
import com.test.entities.MyTest;
import com.test.exception.ProjException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/mytest")
@EnableAutoConfiguration
public class MyTestController {

    @Autowired
    private MyTestRepository testDao;

    @Value(("${com.test.paginatio.max-per-page}"))
    Integer maxPerPage;

    @RequestMapping(value = "/findAll",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public JSON findAll(){
       JSONObject js = new JSONObject();
       js.put("list",testDao.findAll());
       js.put("code","100");
       js.put("desc","success");
       return js;
//        return "ok";
    }
    //建立一个列表和一个详情，存在对应关系
    @RequestMapping(value = "/parseProjectCsvToUserList",method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public  JSON parseProjectCsvToUserList(HttpServletRequest request, MultipartFile file) throws ProjException{
        String fileName = file.getOriginalFilename();
        String postfix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        if (!postfix.equals(".csv")) {
            throw new ProjException("请选择.csv格式的Excel表格文件导入！");
        }
        List<MyTest> dataList = new ArrayList<MyTest>();
        MyTest mytest = null;
        CsvReader r;
        try{
            r = new CsvReader(file.getInputStream(),',', Charset.forName("GBK"));
            r.readHeaders();
            String[] headers = r.getHeaders();
            String error = "导入文件与项目模板不一致！";
            if(!headers[0].equals("sno")) { throw new ProjException(error+"第一列应是sno"); }
            if(!headers[1].equals("sname")) { throw new ProjException(error+"第二列应是sname"); }
            if(!headers[2].equals("sex")) { throw new ProjException(error+"第三列应是sex"); }
            if(!headers[3].equals("备注")) { throw new ProjException(error+"第四列应是备注"); }
            if(!headers[4].equals("计划开始时间")) { throw new ProjException(error+"第六列应是计划开始时间"); }
            SimpleDateFormat sm = new SimpleDateFormat("yyyy/MM/dd");
            //逐条读取记录，直至读完
            while (r.readRecord()) {
                mytest=new MyTest();
                mytest.setSno(Integer.parseInt(r.get(0)));
                mytest.setSname(r.get(1));
                mytest.setSex(r.get(2));
                mytest.setOther(r.get(3));
                mytest.setTitle(fileName+System.currentTimeMillis());
               String data = r.get(4);
                if(!"".equals(data) && data!=null) {
                    mytest.setCreatedTime(sm.parse(r.get(4)));//还有个项目创建日期
                }
                dataList.add(mytest);
            }
        } catch (IOException e) {
            throw new ProjException("[项目数据]批量导入csv异常!");
        } catch (ParseException e) {
            e.printStackTrace();
            throw new ProjException("日期转换异常!清填写正确时间格式！。");
        }
        List stu = testDao.save(dataList);
        JSONObject js = new JSONObject();
        js.put("list",stu);
        return js;
    }

    public  JSON findById(HttpServletRequest request, MultipartFile file) throws ProjException{

        return null;
    }

}

